import random

from django.http import HttpResponse, JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View

from libs.rl_sms import send_message
from libs.captcha.captcha import captcha
from redis import StrictRedis


# 生成图形验证码
class ImageCodeView(View):
    """图形验证码"""

    def get(self, request, uuid):
        """
        :param request: 请求对象
        :param uuid: 唯一标识图形验证码所属于的用户
        :return: image/jpg
        """
        # 生成图片,及答案
        text, image = captcha.generate_captcha()

        # 保存答案和uuid到redis中
        client = StrictRedis()  # 127.0.0.1 6379
        client.set(uuid, text)

        return HttpResponse(image, content_type='image/jpeg')
        pass


# 发送短信验证码
class SMSCodeView(View):
    """短信验证码"""

    def get(self, reqeust, mobile):
        # 接收参数
        image_code = reqeust.GET.get('image_code')
        uuid = reqeust.GET.get('uuid')
        # 校验参数
        if not all([mobile,image_code,uuid]):
            return JsonResponse({'code': '999', 'msg': '缺少参数'})
        # 判断图形验证码
        # 1. 从redis取
        client = StrictRedis()
        redis_image_code = client.get(uuid)  # bytes
        # 2. 从redis删除
        client.delete(uuid)
        # 3. 对比
        if redis_image_code:
            redis_image_code = redis_image_code.decode()
        else:
            redis_image_code = None
        if image_code.upper()==redis_image_code:
            pass
        else:
            return JsonResponse({'code': '999', 'msg': '图形验证码不正确'})

        # 生成短信验证码
        sms_code = '%04d'%random.randint(0, 9999)  # 0000 -> 9999
        # 把短信存到redis中
        client.setex(mobile,5*60,sms_code)
        print('短信验证码为:',sms_code)
        # 发送短信验证码
        # send_message(mobile, sms_code, '5')
        # import sys
        # import os
        # from meiduo.settings import BASE_DIR
        # sys.path.insert(0,os.path.join(BASE_DIR, '../celery_task/'))
        # from main import send_sms_code
        # send_sms_code.delay(mobile, sms_code, '5')
        # 15631120172
        return JsonResponse({'code': '0', 'msg': 'ok'})
